﻿package com.devilcat.ws
{
	import com.worlize.websocket.*;
	import flash.utils.ByteArray;
	import com.adobe.serialization.json.JSONDecoder;
	import com.adobe.serialization.json.JSONEncoder;
	import com.devilcat.dt.Gamedt;
	public class Basicws
	{
		var websocket:WebSocket;
		var mProtocol:String;
		
		public function Basicws(protocol:String)
		{
			mProtocol=protocol;
			websocket = new WebSocket("ws://127.0.0.1:44","*",mProtocol);
			websocket.addEventListener(WebSocketEvent.CLOSED, handleWebSocketClosed);
			websocket.addEventListener(WebSocketEvent.OPEN, handleWebSocketOpen);
			websocket.addEventListener(WebSocketEvent.MESSAGE, handleWebSocketMessage);
			websocket.addEventListener(WebSocketErrorEvent.CONNECTION_FAIL, handleConnectionFail);
			websocket.connect();
		}
		public function closeConnect(){			
			websocket.close(false);
		}
		public function pureString(str:String):String
		{
			var rex:RegExp = /(\t|\n|\r)/gi;
			var str = str.replace(rex,'');
			return str;
		}
		public function debug(tx:String){			
			//Gamedt.MainUI.debugtxt.text=tx+"\n"+Gamedt.MainUI.debugtxt.text;
		}
		public function JSONString(input:Object):String{
			return new JSONEncoder(input).getString();
		}
		public function JSONObject(input:String):*{
			return new JSONDecoder( input, true ).getValue();
		}
		function handleWebSocketOpen(event:WebSocketEvent):void
		{
//			trace("Connected");
//			websocket.sendUTF("Hello World!\n");
//
//			var binaryData:ByteArray = new ByteArray();
//			binaryData.writeUTF("Hello as Binary Message!");
//			websocket.sendBytes(binaryData);
		}

		function handleWebSocketClosed(event:WebSocketEvent):void
		{
			//trace("Disconnected");
		}

		private function handleConnectionFail(event:WebSocketErrorEvent):void
		{
			//trace("Connection Failure: " + event.text);
			//debug("Connection Failure: " + event.text);
		}

		function handleWebSocketMessage(event:WebSocketEvent):void
		{
			if (event.message.type === WebSocketMessage.TYPE_UTF8)
			{
				trace("Got message: " + event.message.utf8Data);
			}
			else if (event.message.type === WebSocketMessage.TYPE_BINARY)
			{
				trace("Got binary message of length " + event.message.binaryData.length);
			}
		}
	}
}